Leaflet is the leading open-source JavaScript library for mobile-friendly interactive maps. Weighing just about 38 KB of JS, it has all the mapping features most developers ever need.
Leaflet is designed with simplicity, performance and usability in mind. It works efficiently across all major desktop and mobile platforms, can be extended with lots of plugins, has a beautiful, easy to use and well-documented API and a simple, readable source code that is a joy to contribute to.
Leaflet is one of the most popular open-source JavaScript libraries for interactive maps. Itâs used by websites ranging from The New York Times and The Washington Post to GitHub and Flickr, as well as GIS specialists like OpenStreetMap, Mapbox, and CartoDB.
This R package makes it easy to integrate and control Leaflet maps in R.
A cheatsheet for this package is here: https://ugoproto.github.io/ugo_r_doc/leaflet-cheat-sheet.pdf
## Loading required package: leaflet
## Loading required package: DT
## Loading required package: readr
## Loading required package: leaflet.extras
You can get more information on the using the Leaflet library in r from the Leaflet Github Repository.
You can get more information on Leaflet from the Leaflet website. This github also has some helpful examples
The first thing to do when buiding leaflet maps in r is to install the leaflet package using install.packages, then attach it using the Library function.
install.packages("leaflet")
library(leaflet)
You create a Leaflet map with these basic steps:
Create a map widget by calling leaflet().
Hereâs a basic example:
m <- leaflet() %>%
# Add default OpenStreetMap map tiles
addTiles() %>%
# add a marker for Buckhingham palace
addMarkers(lng=-0.1419, lat=51.5014, popup="Buckingham Palace, London")
m # Print the map
The easiest way to add tiles is by calling addTiles() with no arguments; by default, OpenStreetMap tiles are used.
There are a range of popular free third-party basemaps which can be added using the addProviderTiles() function, which is implemented using the leaflet-providers plugin. You can view examples of each base map here.
As a convenience, leaflet also provides a named list of all the third-party tile providers that are supported by the plugin. Just type providers$ and choose from one of the options. You can also use names(providers) to view all of the options.
The example below uses the ESRI World Top Map as a basemap. It also uses the setView function to set the intial position and zoom level of the map. If you do not call the setView function, the default view will include any markers you have placed on the map. As the example below does not have any markers, I have used setView to focus on a specific area rather than the intial view showing the whole world.
setView allows you to specify a point on the map that you want your leaflet map to centre on. You can get centre point coordinates, including box boundary coordinates, in many different CRS here: http://bboxfinder.com
m <- leaflet() %>%
#Use the Esri World Topo Map as the basemap
addProviderTiles(providers$Esri.WorldTopoMap)%>%
# Setview sets the intial position of the map to Scotland
setView(lng = -5.394, lat = 56.821, zoom = 6)
# Print the map
m
This example loads the location of the 32 NFL franchises and plots them on a map.
The data is in csv format and contains four columns:
You can explore the data here
## Parsed with column specification:
## cols(
## Team = col_character(),
## Confrence = col_character(),
## Lat = col_double(),
## Lon = col_double()
## )
By loading the data from the csv and passing it to leaflet we can display it as markers on the map.
#Load the NFL data from the csv file
teams <- read_csv("data/nfl_franchises.csv")
## Parsed with column specification:
## cols(
## Team = col_character(),
## Confrence = col_character(),
## Lat = col_double(),
## Lon = col_double()
## )
m <- leaflet(teams) %>%
# Add default OpenStreetMap map tiles
addTiles() %>%
addCircles(~Lon, ~Lat, popup=teams$Team, weight = 3, radius=40,
color="#C83803", stroke = TRUE, fillOpacity = 1)
m # Print the map
RLeaflet is a basic leaflet package that can be augmented with additional functions from the “leaflet.extras” packages. Installing this package will add a lot of extra features to the leaflet package, such as making a heatmat of your data.
The leaflet.extras package is already installed, so lets view the ‘quakes’ dataset that is included in RStudio;
## lat long depth mag stations
## 1 -20.42 181.62 562 4.8 41
## 2 -20.62 181.03 650 4.2 15
## 3 -26.00 184.10 42 5.4 43
## 4 -17.97 181.66 626 4.1 19
## 5 -20.42 181.96 649 4.0 11
## 6 -19.68 184.31 195 4.0 12
As our data has WGS84 lat/long data, leaflet can project it without any issues. Using the leaflet.extras fucntion “addWebGLHeatmap” we can display the quakes data in a heatmap. To make the best use of the heatmap we should use a basemap that complements it. See https://leaflet-extras.github.io/leaflet-providers/preview/ for a list of available basemaps for leaflet.extras.
We’ll use the ESRI WorldImagery map and set the intensity of the heat according to the magnitude of the measured earthquakes to get an idea of where the quakes are at their worst;
leaflet(quakes) %>% addProviderTiles(providers$Esri.WorldImagery) %>%
setView( 178, -20, 5 ) %>%
addHeatmap(lng = ~long, lat = ~lat, intensity = ~mag,
blur = 25, max = 0.05, radius = 12)
RLeaflet can ‘cluster’ points together to provide an aggregated view. This can be quite hard to understand without the aid of an example, so let’s use UK accidents data from 2017.
This is freely available data that provides details of approximately 130,000 accident locations across the UK, including speed, number of vehicles involved and several more variables. A csv of the data is available in this repository.
uk_acc_2017 <- read_csv("uk_accidents_2017.csv")
## Parsed with column specification:
## cols(
## .default = col_double(),
## Date = col_character(),
## Time = col_time(format = ""),
## `Local_Authority_(Highway)` = col_character(),
## LSOA_of_Accident_Location = col_character()
## )
## See spec(...) for full column specifications.
#remove missing values from lat/long
uk_acc_2017 <- uk_acc_2017[complete.cases(uk_acc_2017[, 4:5]),]
head(uk_acc_2017[,4:12])
## # A tibble: 6 x 9
## Longitude Latitude Police_Force Accident_Severi~ Number_of_Vehic~
## <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 -0.0801 51.7 1 1 2
## 2 -0.174 51.5 1 3 2
## 3 -0.0530 51.5 1 3 3
## 4 -0.0607 51.6 1 3 2
## 5 -0.0724 51.6 1 2 1
## 6 -0.354 51.4 1 3 2
## # ... with 4 more variables: Number_of_Casualties <dbl>, Date <chr>,
## # Day_of_Week <dbl>, Time <time>
Lets do a simple plot of the points on a map to see how the raw data looks;
## Assuming "Longitude" and "Latitude" are longitude and latitude, respectively
Striking but not very easy to interpret. There are so many points that much of the land is completely covered, making it very difficult to understand how accidents are spread across the country.
Next, lets add the clustering function to aggregate some of those points together;
leaflet(uk_acc_2017) %>%
# Use OpenStreetMap as the basemap
addProviderTiles(providers$OpenStreetMap.Mapnik)%>%
setView(lng = -4, lat = 54, zoom = 7) %>%
# Add clustered points to the map
addMarkers(clusterOptions = markerClusterOptions() )
## Assuming "Longitude" and "Latitude" are longitude and latitude, respectively
Try zooming in and out. Notice how the clustering is amended depending on zoom level? Clustering makes the data easier to interpret. Hover over one of the numbered points and you will see the outline of the area that it represents.